<template>
  <div class="amap-page-container">
    <el-amap
      ref="map"
      :map-style="defaultConfig.map"
      :center="center"
      :zoom="zoom"
      view-mode="3D"
      class="amap-demo"
      @init="init"
      @mousewheel="changeZoom"
    >
      <!-- 卫星图层 -->
      <el-amap-layer-satellite :visible="showLayer"></el-amap-layer-satellite>

      <!-- 搜索框 -->
      <!-- <div :class="['map_botton', 'map_icon', 'map_search', isSearch ? 'map_search_width' : '']" id="map_search">
        <i class="el-icon-search" @click="changeIsSearch"></i>
        <div v-show="isSearch">
          <el-autocomplete
            clearable
            v-model="deviceName"
            :fetch-suggestions="querySearch"
            placeholder="请输入园区名称"
            :trigger-on-focus="false"
            @select="handleSelect"
          ></el-autocomplete>
        </div>
      </div> -->

      <!-- 缩放工具 -->
      <el-amap-control-tool-bar
        @show="showControl"
        :visible="true"
        :position="{ top: '3vh', left: '1vw' }"
      ></el-amap-control-tool-bar>

      <!-- 切换图层 -->
      <div class="changeLayer">
        <div>
          <img
            class="img-style"
            style="height:100%"
            width="35px"
            height="35px"
            :src="require(`../../assets/map-style/${defaultConfig.src}`)"
          />
        </div>
        <div v-for="item in mapStyle" :key="item.src" class="select-style">
          <el-tooltip effect="dark" :content="item.label" placement="top-start">
            <img
              class="img-style"
              style="height:100%"
              width="35px"
              height="35px"
              :src="require(`../../assets/map-style/${item.src}`)"
              @click="changeMap(item)"
            />
          </el-tooltip>
        </div>
      </div>

      <!-- 聚合点 -->
      <el-amap-marker-cluster :points="points" @click="clickCluster" :maxZoom="20" id="cluster">
      </el-amap-marker-cluster>

      <!-- 点标记 -->
      <el-amap-marker
        v-for="(marker, index) in marker"
        :key="index"
        :position="marker.position"
        :visible="selectAlert"
        @click="clickMarker"
        @init="initMarker"
        :content="setIcon(marker.status)"
      >
      </el-amap-marker>

      <!-- 告警弹窗 -->
      <warn-box :visible="showWarnDialog" :systemMsg="warnDetail" @close="close"></warn-box>

      <!-- 预警统计 -->
      <warn-count :warnCount="warnCount"></warn-count>

      <!-- 设备告警类型 -->
      <div class="deviceStatus" @click="openStatusBox">
        <el-tooltip :disabled="showStatusBox" effect="dark" content="传感器状态" placement="top-start"
          ><a class="el-icon-bangzhu"></a
        ></el-tooltip>
      </div>
      <div class="statusBox" v-show="showStatusBox">
        <el-button @click="fire" :style="huojing ? 'background:#e9eef5' : ''"
          ><span class="circle" style="background:#F56C6C"></span>火警</el-button
        ><el-button @click="abnormal" :style="yichang ? 'background:#e9eef5' : ''"
          ><span class="circle" style="background:#E6A23C"></span>异常</el-button
        >
      </div>
      <!-- 设备类型 -->
      <el-row :gutter="10" class="deviceTypeChoose">
        <el-col
          :span="6"
          class="selected"
          @click.native="allDevice"
          :style="quanbu ? 'background:#409eff;color:#FFFFFF' : ''"
          ><el-tooltip :disabled="quanbu" effect="dark" content="全部" placement="top-start"
            ><a class="el-icon-house"></a></el-tooltip
        ></el-col>
        <el-col
          :span="6"
          class="selected"
          @click.native="wenGan"
          :style="wengan ? 'background:#409eff;color:#FFFFFF' : ''"
          ><el-tooltip :disabled="wengan" effect="dark" content="温感" placement="top-start"
            ><a class="el-icon-cpu"></a></el-tooltip
        ></el-col>
        <el-col
          :span="6"
          class="selected"
          @click.native="yanWu"
          :style="yanwu ? 'background:#409eff;color:#FFFFFF' : ''"
          ><el-tooltip :disabled="yanwu" effect="dark" content="烟雾" placement="top-start"
            ><a class="el-icon-smoking"></a></el-tooltip
        ></el-col>
        <el-col
          :span="6"
          class="selected"
          @click.native="shouBao"
          :style="shoubao ? 'background:#409eff;color:#FFFFFF' : ''"
          ><el-tooltip :disabled="shoubao" effect="dark" content="手报" placement="top-start"
            ><a class="el-icon-heavy-rain"></a></el-tooltip
        ></el-col>
      </el-row>

      <!-- 设备列表弹窗 -->
      <el-amap-info-window
        :visible.sync="infoWindow"
        :position="infoWinPosition"
        :offset="[230, 20]"
        :autoMove="true"
        :closeWhenClickMap="true"
        :isCustom="true"
      >
        <div v-if="isCluster" class="info-window">
          <div class="info-window-title" style="color:#5d5d5d">传感器{{ deviceNum }}个</div>
          <div class="info-window-list-container">
            <el-row
              class="info-window-list"
              v-for="(item, index) in deviceList"
              :key="index"
              @click.native="openDetail(item)"
              ><a
                style="color:#409EFF"
                :class="[
                  'info-window-list-icon',
                  item.deviceTypeName == '温感'
                    ? 'el-icon-cpu'
                    : item.deviceTypeName == '烟感'
                    ? 'el-icon-smoking'
                    : item.deviceTypeName == '手报'
                    ? 'el-icon-heavy-rain'
                    : ''
                ]"
              ></a
              >{{ item.deviceName }}</el-row
            >
          </div>
        </div>
        <div v-else class="info-window" style="background-image: linear-gradient(270deg, #f35a58 0%, #f37958 100%);">
          <div class="info-window-list-container">
            <el-row
              class="info-window-list"
              v-for="(item, index) in alertList"
              :key="index"
              @click.native="openAlertDetail(item)"
              ><a
                style="color:#409EFF"
                :class="[
                  'info-window-list-icon',
                  item.deviceTypeName == '温感'
                    ? 'el-icon-cpu'
                    : item.deviceTypeName == '烟感'
                    ? 'el-icon-smoking'
                    : item.deviceTypeName == '手报'
                    ? 'el-icon-heavy-rain'
                    : ''
                ]"
              ></a
              >{{ item.deviceName }}</el-row
            >
          </div>
        </div>
      </el-amap-info-window>

      <!-- 设备详情弹窗 -->
      <div>
        <i style="font-size:1.8rem" :class="detailWindow ? 'el-icon-close' : ''" @click="closeDetail"></i>
        <el-card v-show="detailWindow" class="detail-card">
          <el-row class="detail-card-title" style="background:#409EFF;border-radius:2px"
            ><a
              :class="[
                'detail-card-title-icon',
                detailList.deviceTypeName == '温感'
                  ? 'el-icon-cpu'
                  : detailList.deviceTypeName == '烟感'
                  ? 'el-icon-smoking'
                  : detailList.deviceTypeName == '手报'
                  ? 'el-icon-heavy-rain'
                  : ''
              ]"
            ></a
            >{{ detailTitle }}</el-row
          >
          <el-row
            ><el-tabs :stretch="true" v-model="activeName">
              <el-tab-pane label="关联摄像机" name="first">
                <iframe
                  :src="detailList.streamUrl"
                  height="100%"
                  width="100%"
                  allowfullscreen
                  allow="autoplay; fullscreen; microphone;"
                ></iframe>
              </el-tab-pane>
              <el-tab-pane label="预警事件" name="second">
                <el-table :data="detailList.equipmentCollectAlertList" class="warnTab">
                  <el-table-column prop="deviceAddress" label="报警地点"> </el-table-column>
                  <el-table-column prop="alarmCause" label="报警原因"> </el-table-column>
                  <el-table-column prop="alertTimeStr" label="报警时间"> </el-table-column>
                </el-table>
              </el-tab-pane>

              <el-tab-pane label="基本信息" name="third">
                <el-descriptions :column="1" border :labelStyle="{ width: '100px' }">
                  <el-descriptions-item label="设备类型">{{ detailList.deviceTypeName }}</el-descriptions-item>
                  <el-descriptions-item label="设备编号">{{ detailList.deviceSource }}</el-descriptions-item>
                  <el-descriptions-item label="设备名称">{{ detailList.deviceName }}</el-descriptions-item>
                  <el-descriptions-item label="厂家">{{ detailList.manufactor }} </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
            </el-tabs>
          </el-row>
        </el-card>
      </div>
    </el-amap>
  </div>
</template>

<script>
import mapApi from '@/api/gaode-map'
import WarnCount from './component/WarnCount.vue'
import WarnBox from '@/components/WarningInfo/index.vue'
// import WarnBox from './component/WarnBox.vue'

export default {
  components: { WarnCount, WarnBox },
  data() {
    return {
      alertName: '', //告警设备名称
      alertDeviceSource: '', //告警设备编号
      isCluster: true, //信息窗体类型
      selectAlert: false, //选择设备告警状态
      showStatusBox: false, //显示设备状态窗口
      //选中改变背景颜色
      quanbu: true,
      wengan: false,
      yanwu: false,
      shoubao: false,
      huojing: false,
      yichang: false,
      map: null, //初始化地图
      markers: null,
      zoom: 17,
      center: [108.27947273101331, 22.85713439190149],
      infoWinPosition: [108.27947273101331, 22.85713439190149], //信息窗体位置
      deviceType: '', //设备类型
      deviceStatus: '', //设备告警状态入参 1-异常 2-火警
      isSearch: false,
      deviceName: '', //搜索框
      coordinatesData: [], //聚合点数据
      warnCount: {}, //预警统计
      basicInfo: {}, //设备基本信息
      detailInfo: {}, //设备详情信息
      points: [], //聚合点坐标
      marker: [], //点标注坐标
      infoWindow: false, //聚点信息窗体
      detailWindow: false, //详情窗体
      activeName: 'second',
      detailTitle: '',
      deviceNum: null, //传感器数量
      guidArr: [], //网格id去重
      guid: [], //获取所有设备guid
      deviceList: [], //设备列表
      deviceSource: '', //设备编号
      detailList: [], //设备详情列表
      alertList: [], //告警列表
      warnList: [], //告警弹窗列表
      warnDetail: {},
      showWarnDialog: false,
      timer: null, //定时器
      showLayer: false,
      mapStyle: [
        { src: 'normal.png', label: '标准图层' },
        { src: 'black.png', label: '幻夜黑' },
        { src: 'satellite.png', label: '卫星图层' }
      ],
      defaultConfig: {
        map: '',
        src: 'normal.png',
        title: '标准图层'
      }
    }
  },
  watch: {
    warnList(newVal, oldVal) {
      if (newVal.length > oldVal.length) {
        this.showWarnDialog = true
        this.warnDetail = newVal[0]
      }
    }
  },
  mounted() {
    this.timer = setInterval(() => {
      this.getCoordinatesAndWarn()
      // this.getWarnList()
    }, 10000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  created() {
    this.getCoordinatesAndWarn()
    // this.getWarnList()
  },
  methods: {
    // 关闭告警弹窗
    close(data) {
      this.showWarnDialog = data
    },
    // 获取告警弹窗列表
    getWarnList() {
      mapApi.getAlertList().then(res => {
        if (res.status === 200) {
          this.warnList = res.data.data.rows
        }
      })
    },
    // 标记样式
    setIcon(value) {
      if (value == '2') {
        const content = `<svg t="1650444305892" class="icon" viewBox="0 0 1026 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2622" width="50" height="50"><path d="M490.2 445.2c0-18 12.6-32.9 28-32.9 15.5 0 28 13.1 28 31.1l0 178.8c0 18-12.6 30.2-28 30.2-15.5 0-28-12-28-29.9L490.2 445.2zM518.7 747.4c-17.1 0-30.9-14.1-30.9-31.6 0-17.4 13.8-31.6 30.9-31.6 17.1 0 30.9 14.1 30.9 31.6C549.6 733.3 535.8 747.4 518.7 747.4L518.7 747.4z" p-id="2623" fill="#d81e06" data-spm-anchor-id="a313x.7781069.0.i0" class="selected"></path><path d="M568.832 196.608c20.992 35.328 333.312 560.64 349.184 587.776 14.336 24.064 14.336 47.104 6.656 61.952-8.704 16.384-29.696 21.504-52.736 21.504-18.944 0-678.912 0-709.632 0-28.16 0-49.152-7.68-55.296-19.968-7.68-16.384-6.144-37.888 11.264-67.072C137.216 749.056 447.488 216.064 457.728 199.68c15.36-26.112 37.376-43.52 57.856-43.52C536.064 156.16 556.544 176.64 568.832 196.608zM502.272 252.416c-11.776 19.968-302.08 513.024-316.928 537.088-6.656 11.264-8.192 17.92 6.656 17.92 44.544 0 602.624 0 645.632 0 14.336 0 15.872-8.192 9.728-18.432-25.088-41.472-308.736-518.144-321.024-537.6C514.56 231.936 514.048 232.448 502.272 252.416z" p-id="2624" fill="#d81e06"></path></svg>`
        return content
      }
      if (value == '1') {
        const content = `<img src="https://iphoto.macsc.com/icon/icon/256/20200601/79633/3283133.png" style="display:flex;width:2vw"/>`
        return content
      }
    },

    // 设备告警类型
    fire() {
      this.infoWindow = false
      this.deviceStatus = '2'
      this.deviceType = ''
      this.huojing = true
      this.yichang = false
      this.quanbu = true
      this.wengan = false
      this.yanwu = false
      this.shoubao = false
      this.selectAlert = true

      this.getCoordinatesAndWarn()

      // 视觉跟踪
      if (this.alertList.length > 0) {
        this.map.setCenter([this.alertList[0].longitude, this.alertList[0].latitude])
      }
      this.map.setZoom(17)
    },
    abnormal() {
      this.deviceStatus = '1'
      this.deviceType = ''
      this.huojing = false
      this.yichang = true
      this.quanbu = true
      this.wengan = false
      this.yanwu = false
      this.shoubao = false
      this.selectAlert = true
      this.infoWindow = false

      this.getCoordinatesAndWarn()

      // 视觉跟踪
      if (this.alertList.length > 0) {
        this.map.setCenter([this.alertList[0].longitude, this.alertList[0].latitude])
      }
      this.map.setZoom(17)
    },

    // 显示设备告警类型窗口
    openStatusBox() {
      this.showStatusBox = !this.showStatusBox
    },

    // 选择设备类型
    allDevice() {
      this.deviceType = ''
      this.deviceStatus = ''
      this.selectAlert = false
      this.infoWindow = false
      //选中改变背景
      this.huojing = false
      this.yichang = false
      this.quanbu = true
      this.wengan = false
      this.yanwu = false
      this.shoubao = false

      this.getCoordinatesAndWarn()

      // 视觉跟踪
      this.map.setCenter([108.27947273101331, 22.85713439190149])
      this.map.setZoom(15)
    },
    wenGan() {
      this.deviceType = '1'
      this.deviceStatus = ''
      this.selectAlert = false
      this.infoWindow = false
      //选中改变背景
      this.huojing = false
      this.yichang = false
      this.quanbu = false
      this.wengan = true
      this.yanwu = false
      this.shoubao = false

      this.getCoordinatesAndWarn()

      // 视觉跟踪
      if (this.coordinatesData.length > 0) {
        this.map.setCenter([this.coordinatesData[0].data.longitude, this.coordinatesData[0].data.latitude])
      }
      this.map.setZoom(15)
    },
    yanWu() {
      this.deviceType = '2'
      this.deviceStatus = ''
      this.selectAlert = false
      this.infoWindow = false
      //选中改变背景
      this.huojing = false
      this.yichang = false
      this.quanbu = false
      this.wengan = false
      this.yanwu = true
      this.shoubao = false

      this.getCoordinatesAndWarn()

      // 视觉跟踪
      if (this.coordinatesData.length > 0) {
        this.map.setCenter([this.coordinatesData[0].data.longitude, this.coordinatesData[0].data.latitude])
      }
      this.map.setZoom(15)
    },
    shouBao() {
      this.deviceType = '3'
      this.deviceStatus = ''
      this.selectAlert = false
      this.infoWindow = false
      //选中改变背景
      this.huojing = false
      this.yichang = false
      this.quanbu = false
      this.wengan = false
      this.yanwu = false
      this.shoubao = true

      this.getCoordinatesAndWarn()

      // 视觉跟踪
      if (this.coordinatesData.length > 0) {
        this.map.setCenter([this.coordinatesData[0].data.longitude, this.coordinatesData[0].data.latitude])
      }
      this.map.setZoom(15)
    },

    // 打开设备详情
    openDetail(item) {
      // //console.log(item);
      this.deviceSource = item.deviceSource
      this.detailTitle = item.deviceName
      this.detailWindow = true
      this.getEquipmentMapDetail()
    },
    // 打开告警设备详情
    openAlertDetail(item) {
      this.deviceSource = item.deviceSource
      this.detailTitle = item.deviceName
      this.detailWindow = true
      this.getEquipmentMapDetail()
    },

    // 关闭详情窗口
    closeDetail() {
      this.detailWindow = false
    },

    // 点击聚合点打开信息窗体
    clickCluster(lnglat) {
      this.guid = []
      this.deviceNum = lnglat.clusterData.length //传感器个数
      console.log(lnglat, '聚合点')
      this.infoWinPosition = [lnglat['lnglat']['lng'], lnglat['lnglat']['lat']]

      // 根据网格经纬度获取guid，并获取设备列表
      this.coordinatesData.forEach(e => {
        if (
          e.data.longitude.toFixed(6) == this.infoWinPosition[0] &&
          e.data.latitude.toFixed(6) == this.infoWinPosition[1]
        ) {
          this.guid.push(e.data.guid)
        }
      })
      // guid去重
      this.guidArr = [...new Set(this.guid)] // 好方法

      // 视觉跟踪
      this.map.setCenter([lnglat['lnglat']['lng'], lnglat['lnglat']['lat']])
      if (this.map.getZoom() != 17) {
        this.map.setZoom(17)
      } else {
        this.infoWindow = !this.infoWindow
      }

      this.isCluster = true
      this.getGridCoordinateDetail()
    },

    // 点击点标记打开信息窗体
    clickMarker(MapsEvent) {
      this.guid = []
      console.log(MapsEvent)
      this.infoWinPosition = [MapsEvent.target._position[0], MapsEvent.target._position[1]]
      this.alertList.forEach(e => {
        if (e.longitude == MapsEvent.target._position[0] && e.latitude == MapsEvent.target._position[1]) {
          this.guid.push(e.gridMount)
        }
      })
      // guid去重
      this.guidArr = [...new Set(this.guid)] // 好方法

      // 视觉跟踪
      this.map.setCenter([MapsEvent.target._position[0], MapsEvent.target._position[1]])
      if (this.map.getZoom() != 17) {
        this.map.setZoom(17)
      } else {
        this.infoWindow = true
      }

      this.isCluster = false
      this.getGridCoordinateDetail()
    },

    // 获取设备坐标，预警统计
    async getCoordinatesAndWarn() {
      // 重置数组
      this.points = []
      this.guidArr = []
      this.guid = []
      this.marker = []

      await mapApi
        .gridCoordinate({
          zoom: this.zoom,
          deviceType: this.deviceType,
          deviceStatus: this.deviceStatus
        })
        .then(res => {
          if (res.status === 200) {
            this.coordinatesData = res.data.data.list
            this.alertList = res.data.data.alertList
            this.warnCount = res.data.data.count[0]
          }
        })

      // console.log(this.alertList, '告警列表')

      // 获取聚合点坐标
      this.coordinatesData.forEach(e => {
        let trans = this.lnglat_cal(e.data.longitude, e.data.latitude) // 转换坐标(百度-->高德)
        this.points.push({ lnglat: [trans.lng, trans.lat] })
        e.data.longitude = trans.lng
        e.data.latitude = trans.lat
      })

      // 获取告警设备坐标
      this.alertList.forEach(e => {
        let trans = this.lnglat_cal(e.longitude, e.latitude) // 转换坐标(百度-->高德)
        this.marker.push({
          position: [trans.lng, trans.lat],
          guid: e.gridMount,
          status: e.deviceStatus
        })
        e.longitude = trans.lng
        e.latitude = trans.lat
      })
    },

    // 获取设备列表
    async getGridCoordinateDetail() {
      this.deviceList = []
      await mapApi
        .gridCoordinateDetail({
          guids: this.guidArr,
          deviceType: this.deviceType
        })
        .then(res => {
          if (res.status == 200) {
            this.deviceList = res.data.data
          }
        })
    },

    // 获取设备详情
    async getEquipmentMapDetail() {
      await mapApi
        .equipmentMapDetail({
          deviceSource: this.deviceSource
        })
        .then(res => {
          if (res.status == 200) {
            this.detailList = res.data.data[0]
          }
        })
    },

    // 初始化地图
    init(map) {
      map.setZooms([2, 17])
      this.map = map
    },

    // 监听地图层级变化
    changeZoom(zoom) {
      let temp = this.map.getZoom()
      if (temp < 17) {
        this.infoWindow = false
      }
    },

    // 初始化点标记
    initMarker(marker) {},

    // 比例尺
    showControl() {},

    // 弹出搜索框
    changeIsSearch() {
      this.isSearch = !this.isSearch
    },

    // 经纬度换算：百度-->高德
    lnglat_cal(lng, lat) {
      let x = lng - 0.0065,
        y = lat - 0.006,
        x_pi = (3.14159265358979324 * 3000.0) / 180.0

      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi)
      let tempLon = z * Math.cos(theta)
      let tempLat = z * Math.sin(theta)
      return { lng: tempLon, lat: tempLat }
    },
    // 更改图层样式
    changeMap(item) {
      this.defaultConfig.src = item.src
      this.showLayer = false
      switch (item.label) {
        case '幻夜黑':
          this.defaultConfig.map = 'amap://styles/dark'
          break
        case '标准图层':
          this.defaultConfig.map = 'amap://styles/normal'
          break
        case '卫星图层':
          this.showLayer = true
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import './style/gaode-map.scss';
</style>
